<template>
  <div>
    <div class="request" v-if="!addShow && !dtlShow">
      <!-- 筛选按钮 -->
      <div class="search-button">
        <el-button
          v-hasPermi="['system:inorder:query']"
          class="btn search"
          @click="getList"
          ><el-icon class="icon" color="#fff"> <Search /> </el-icon
          >查询</el-button
        >

        <el-button
          v-hasPermi="['system:inorder:add']"
          class="btn search"
          @click="showAdd('add')"
          ><el-icon class="icon" color="#fff"> <Plus /> </el-icon
          >新增</el-button
        >
        <el-button class="btn add" @click="handleRefresh"
          ><el-icon class="icon" color="#fff"> <Refresh /> </el-icon
          >重置</el-button
        >
        <el-popover :width="170" trigger="click" placement="bottom">
          <template #reference>
            <el-button class="btn search" style="width: 100px"
              ><el-icon class="icon" color="#fff"> <Setting /> </el-icon
              >显示列</el-button
            >
          </template>
          <el-checkbox-group v-model="checkList" @change="handleCheckChange">
            <div>
              <el-checkbox label="warehousingApplyCode">入库编号</el-checkbox>
            </div>
            <div>
              <el-checkbox label="applicantDateStr">申请日期</el-checkbox>
            </div>
            <div>
              <el-checkbox label="applicantName">申请人</el-checkbox>
            </div>
            <div>
              <el-checkbox label="deptName">申请部门</el-checkbox>
            </div>
            <div>
              <el-checkbox label="warehousingApplyTypeName"
                >入库类型</el-checkbox
              >
            </div>
            <div>
              <el-checkbox label="contractCode">关联合同</el-checkbox>
            </div>
            <div>
              <el-checkbox label="projectCode">关联项目</el-checkbox>
            </div>
            <div>
              <el-checkbox label="checkStatusName">审核状态</el-checkbox>
            </div>
            <div>
              <el-checkbox label="nextNodeName">下步流程</el-checkbox>
            </div>
          </el-checkbox-group>
        </el-popover>
      </div>
      <!-- 筛选条件 -->
      <div class="search">
        <div class="search-item" style="margin-bottom: 10px">
          <el-input
            clearable
            v-model="params.warehousingApplyCode"
            class="search-input"
            placeholder="请输入入库编号"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.applicantName"
            class="search-input"
            placeholder="请输入申请人"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.contractCode"
            class="search-input"
            placeholder="请输入合同编号"
          ></el-input>
        </div>
        <div class="search-item">
          <el-input
            clearable
            v-model="params.projectName"
            class="search-input"
            placeholder="请输入项目名称"
          ></el-input>
        </div>

        <div class="search-item">
          <el-select
            v-model="params.warehousingApplyType"
            placeholder="请选择入库类型"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in inStatusList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>

        <div class="search-item">
          <el-select
            v-model="params.checkStatus"
            placeholder="请选择审核状态"
            clearable
            class="search-input"
          >
            <el-option
              v-for="dict in auditStatusList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </div>
      </div>

      <!-- 表格数据 -->
      <el-table
        v-loading="loading"
        :data="list"
        border
        height="59.2vh"
        :header-cell-style="{ 'text-align': 'center' }"
        @sort-change="sortChange"
      >
        <el-table-column label="操作" min-width="150px">
          <template #default="{ row }">
            <div class="table-operate">
              <el-icon
                v-if="[0, 5, 6].includes(row.checkStatus)"
                v-hasPermi="['system:inorder:edit']"
                title="编辑"
                color="#FFB700"
                class="table-icon"
                :size="20"
                @click="handleOperate('edit', row)"
              >
                <Edit />
              </el-icon>

              <el-icon
                v-hasPermi="['system:inorder:detail']"
                title="查看详情"
                color="#007CEF"
                class="table-icon"
                :size="20"
                @click="handleOperate('detail', row)"
              >
                <Document />
              </el-icon>

              <el-icon
                v-if="[1].includes(row.checkStatus)"
                v-hasPermi="['system:inorder:revoke']"
                title="撤销"
                color="#BBBBBB"
                class="table-icon"
                :size="20"
                @click="handleOperate('revoke', row)"
              >
                <img
                  src="@/assets/icons/images/repeal.png"
                  style="width: 18px; height: 18px"
                />
              </el-icon>

              <el-icon
                v-hasPermi="['system:inorder:delete']"
                title="删除"
                v-if="[0, 5].includes(row.checkStatus)"
                color="#E33838"
                class="table-icon"
                :size="20"
                @click="handleOperate('delete', row)"
              >
                <Delete />
              </el-icon>
            </div> </template
        ></el-table-column>
        <el-table-column
          type="index"
          label="序号"
          :index="indexMethod"
          width="80"
          align="center"
        />
        <el-table-column
          label="入库编号"
          prop="warehousingApplyCode"
          v-if="checkList.includes('warehousingApplyCode')"
          :show-overflow-tooltip="true"
          min-width="150"
          sortable="custom"
        />
        <el-table-column
          label="申请日期"
          prop="applicantDateStr"
          v-if="checkList.includes('applicantDateStr')"
          :show-overflow-tooltip="true"
          min-width="150"
          sortable="custom"
        />
        <!--:formatter="dateFormat"-->
        <el-table-column
          label="申请人"
          prop="applicantName"
          v-if="checkList.includes('applicantName')"
          :show-overflow-tooltip="true"
          min-width="150"
          sortable="custom"
        />
        <el-table-column
          label="申请部门"
          prop="deptName"
          v-if="checkList.includes('deptName')"
          :show-overflow-tooltip="true"
          min-width="130"
          sortable="custom"
        />
        <el-table-column
          label="入库类型"
          prop="warehousingApplyTypeName"
          v-if="checkList.includes('warehousingApplyTypeName')"
          :show-overflow-tooltip="true"
          min-width="120"
          sortable="custom"
        />
        <el-table-column
          label="关联合同"
          prop="contractCode"
          v-if="checkList.includes('contractCode')"
          :show-overflow-tooltip="true"
          min-width="200"
          sortable="custom"
        >
          <template #default="{ row }">
            <span
              v-if="row.purchaseContractId"
              @click="handleContractCodeDetail(row)"
              style="color: #409eff; cursor: pointer"
              >{{ row.contractCode }}</span
            >
            <span v-else>{{ row.contractCode }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="关联项目"
          prop="projectCode"
          v-if="checkList.includes('projectCode')"
          :show-overflow-tooltip="true"
          min-width="180"
          sortable="custom"
        >
          <template #default="{ row }">
            <span
              v-if="row.projectId"
              @click="handleProjectDetail(row)"
              style="color: #409eff; cursor: pointer"
              >{{ row.projectCode }}</span
            >
            <span v-else>{{ row.projectCode }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="审核状态"
          prop="checkStatusName"
          v-if="checkList.includes('checkStatusName')"
          :show-overflow-tooltip="true"
          min-width="130"
          sortable="custom"
        >
          <template #default="{ row }">
            <span :style="getStatusColor(row.checkStatusName)">{{
              row.checkStatusName
            }}</span>
          </template></el-table-column
        >
        <el-table-column
          label="下步流程"
          prop="nextNodeName"
          v-if="checkList.includes('nextNodeName')"
          :show-overflow-tooltip="true"
          min-width="150"
          sortable="custom"
        />
      </el-table>

      <!-- 分页 -->
      <pagination
        class="pagination"
        :total="total"
        v-model:page="params.pageNum"
        v-model:limit="params.pageSize"
        @pagination="getList"
      />
    </div>

    <InorderAdd
      ref="inorderAddRef"
      v-if="addShow"
      v-model:addShow="addShow"
      @refreshList="getList"
      :pageType="pageType"
    />

    <InorderDtl
      ref="inorderDtlRef"
      v-if="dtlShow"
      v-model:dtlShow="dtlShow"
      @refreshList="getList"
      :pageType="pageType"
    />
  </div>
</template>

<script setup>
import InorderAdd from "./add.vue";
import InorderDtl from "./dtl.vue";
import { getDictsApi } from "@/api/dict";
import {
  getInorderListApi,
  deleteOrder,
  saveCancel,
} from "@/api/stock/inorder";
import { useMouseInElement } from "@vueuse/core";
import { addTableHeaderApi, getTableHeaderApi } from "@/api/pub";
import { ElMessage, ElMessageBox } from "element-plus";
// 路由
const route = useRoute();
const router = useRouter();
// 搜索参数
const params = reactive({
  warehousingApplyCode: null,
  applicantName: null,
  contractCode: null,
  projectName: null,
  warehousingApplyType: null,
  checkStatus: null,
  inStatus: null,
  type: 1,
  pageNum: 1,
  pageSize: 50,
  sortField: "",
  sortOrder: "",
});
// 表格加载效果
const loading = ref(false);
// 数据list列表
const list = ref([]);
// 审核状态
const inStatusList = ref([]);
// 审核状态
const auditStatusList = ref([]);
// 总数
const total = ref(0);
// 客户新增组件引用
const inorderAddRef = ref(null);
// 客户新增组件显隐
const addShow = ref(false);
// 操作类型
const pageType = ref("");

const inorderDtlRef = ref(null);

const dtlShow = ref(false);

const checkList = ref([
  "warehousingApplyCode",
  "applicantDateStr",
  "applicantName",
  "deptName",
  "warehousingApplyTypeName",
  "contractCode",
  "projectCode",
  "checkStatusName",
  "nextNodeName",
]);

/**
 * @description: 复选框选中
 */
const handleCheckChange = async (val) => {
  var str = val.join(",");
  const result = await addTableHeaderApi({
    moduleType: 26,
    titleField: str,
  });
};

/**
 * @description: 获取表头
 */
const getTableHeader = async () => {
  const result = await getTableHeaderApi({
    moduleType: 26,
  });
  if (result.code == 200) {
    var arr = result.data.titleField.split(",");
    checkList.value = arr;
  }
};

/**
 * @description: 重置
 */
const handleRefresh = () => {
  Object.assign(params, {
    warehousingApplyCode: null,
    applicantName: null,
    contractCode: null,
    projectName: null,
    warehousingApplyType: null,
    checkStatus: null,
    inStatus: null,
    type: 1,
    pageNum: 1,
    pageSize: 50,
    sortField: "",
    sortOrder: "",
  });
  getList();
};

/**
 * @description: 列表排序
 * @param {*} column.prop //当前排序取的字段
 * @param {*} column.order // "desc" "asc" 正序或倒序
 */
const sortChange = (column) => {
  params.sortField = column.prop;
  if (column.order === "descending") {
    params.sortOrder = "DESC"; // 排序或倒序
  } else {
    params.sortOrder = "ASC"; // 排序或倒序
  }
  getList();
};

/**
 * @description: 获取客户列表
 */
const getList = async () => {
  try {
    loading.value = true;
    let { pageNum, pageSize } = params;
    const res = await getInorderListApi({ pageNum, pageSize }, params);
    list.value = res.rows;
    total.value = res.total;
    loading.value = false;
  } catch {
    loading.value = false;
  }
};
/*dateFormat:function(row,column){
  var date = row[column.property];
  if(date == undefined){
    return "";
  }
  return useMouseInElement(date).format("YYYY-MM-DD")
}*/

const showAdd = async (type) => {
  pageType.value = type;
  addShow.value = true;

  nextTick(() => {
    inorderAddRef.value.showAdd();
  });
};

/**
 * @description: 表格操作
 * @param {String} type 类型
 * @param {Object} row  当前行数据
 */
const handleOperate = async (type, row) => {
  switch (type) {
    case "edit":
      pageType.value = type;
      addShow.value = true;

      nextTick(() => {
        inorderAddRef.value.showEdit(row.id);
      });
      break;
    case "detail":
      pageType.value = type;
      dtlShow.value = true;
      nextTick(() => {
        inorderDtlRef.value.showEdit(row.id);
      });
      break;

    case "delete":
      ElMessageBox.confirm("此操作将删除该请购信息，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
        type: "warning",
      })
        .then(async () => {
          const res = await deleteOrder(row.id);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;
    case "revoke":
      ElMessageBox.confirm("确定撤销该数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "confirmBtnClass",
        cancelButtonClass: "cancelBtnClass",
      })
        .then(async () => {
          const res = await saveCancel(row.id);
          if (res.code === 200) {
            ElMessage.success(res.msg);
            getList();
          } else {
            ElMessage.error(res.msg);
          }
        })
        .catch(() => {});
      break;

    default:
      break;
  }
};
/**
 * @description: 序号
 * @param {Number} index 索引
 */
function indexMethod(index) {
  const currentPage = params.pageNum;
  const pageSize = params.pageSize;
  const truelndex = (currentPage - 1) * pageSize + index + 1;
  return truelndex;
}
/**
 * @description: 获取字典
 */
async function getDicts() {
  // 入库类型
  await getDictsApi("erp_warehousing_apply_type").then((res) => {
    if (res.code === 200) {
      inStatusList.value = res.data;
    }
  });

  // 审核状态
  await getDictsApi("erp_warehousing_check_status").then((res) => {
    if (res.code === 200) {
      auditStatusList.value = res.data;
    }
  });
}
/* 跳转项目详情 */
const handleProjectDetail = (row) => {
  const { href } = router.resolve({
    path: `/sales/project`,
    query: { projectId: row.projectId },
  });
  window.open(href, "_blank");
  // window.open(`/sales/project?projectId=${row.projectId}`, "_blank");
};

/* 跳转合同详情 */
const handleContractCodeDetail = (row) => {
  const { href } = router.resolve({
    path: `/SealManage/contractSeal`,
    query: { purchaseContractId: row.purchaseContractId },
  });
  window.open(href, "_blank");
  // window.open(
  //   `/purchase/contractSeal?purchaseContractId=${row.purchaseContractId}`,
  //   "_blank"
  // );
};
onMounted(() => {
  getDicts();
  getList();
  getTableHeader();
});
</script>
<style>
@import "@/assets/styles/confirmBtn.css";
</style>
<style lang="scss" scoped>
.request {
  padding: 20px;
  width: 100%;
  height: 100%;
  .pagination {
    margin-top: 20px;
  }
  .search {
    flex-wrap: wrap;
  }
}
</style>
